<template>
  <view class="container">
    <!-- 导航栏：返回+标题 -->
    <view class="navbar" :style="{ paddingTop: statusBarHeight + 'px', height: (44 + statusBarHeight) + 'px' }">
      <text class="back-btn" @click="navigateBack">
        <i class="fa fa-angle-left"></i>
      </text>
      <text class="title">{{ isEdit ? '修改工单' : '创建新工单' }}</text>
    </view>

    <!-- 表单容器 -->
    <view class="form-container">
      <!-- 调试信息：显示当前ID状态（正式环境可删除） -->
      <view v-if="isEdit" class="debug-info" style="margin-bottom:15px;color:#f53f3f;font-size:12px;">
        <text>调试：当前工单ID → {{ formData.id || '【ID为空】' }}</text>
      </view>

      <form @submit="submitForm" report-submit>
        <!-- 1. 产品选择（必选） -->
        <view class="form-item">
          <text class="form-label">产品 *</text>
          <picker 
            class="form-picker"
            mode="selector"
            :range="products"
            :range-key="'name'"
            :value="productIndex"
            @change="onProductChange"
          >
            <view class="picker-view">
              {{ productIndex !== null ? products[productIndex].name : '请选择产品' }}
              <i class="fa fa-angle-down"></i>
            </view>
          </picker>
        </view>

        <!-- 2. 工单标题（必选） -->
        <view class="form-item">
          <text class="form-label">工单标题 *</text>
          <view class="input-group">
            <input 
              class="form-input"
              type="text"
              v-model="formData.title"
              maxlength="50"
              @focus="handleFocus('title')"
              @blur="handleBlur('title')"
            />
            <label class="floating-label" :class="{ 'active': isFocus.title || formData.title.trim() }">
              请输入工单标题
            </label>
          </view>
        </view>

        <!-- 3. 联系人（必选） -->
        <view class="form-item">
          <text class="form-label">联系人 *</text>
          <view class="input-group">
            <input 
              class="form-input"
              type="text"
              v-model="formData.name"
              maxlength="20"
              @focus="handleFocus('name')"
              @blur="handleBlur('name')"
            />
            <label class="floating-label" :class="{ 'active': isFocus.name || formData.name.trim() }">
              请输入联系人姓名
            </label>
          </view>
        </view>

        <!-- 4. 联系电话（必选） -->
        <view class="form-item">
          <text class="form-label">联系电话 *</text>
          <view class="input-group">
            <input 
              class="form-input"
              type="number"
              v-model="formData.phone"
              maxlength="11"
              @focus="handleFocus('phone')"
              @blur="handleBlur('phone')"
            />
            <label class="floating-label" :class="{ 'active': isFocus.phone || formData.phone.trim() }">
              请输入11位手机号码
            </label>
          </view>
        </view>

        <!-- 5. 地址（必选） -->
        <view class="form-item">
          <text class="form-label">地址 *</text>
          <view class="input-group">
            <input 
              class="form-input"
              type="text"
              v-model="formData.address"
              maxlength="100"
              @focus="handleFocus('address')"
              @blur="handleBlur('address')"
            />
            <label class="floating-label" :class="{ 'active': isFocus.address || formData.address.trim() }">
              输入地址（如：北京市朝阳区）
            </label>
          </view>
          <button 
            class="map-btn"
            type="default"
            @click="openMapWithCurrentLocation"
            hover-class="map-btn-hover"
          >
            <i class="fa fa-map-marker"></i> 定位当前位置并选点
          </button>
          <text class="parse-status" v-if="formData.longitude">
            <i class="fa fa-check-circle"></i> 地址已解析（可提交）
          </text>
          <text class="parse-status error" v-if="!formData.longitude && formData.address.trim()">
            <i class="fa fa-exclamation-circle"></i> 请等待地址解析或点击定位
          </text>
        </view>

        <!-- 6. 问题描述（必选） -->
        <view class="form-item">
          <text class="form-label">问题描述 *</text>
          <view class="input-group textarea-group">
            <textarea 
              class="form-input"
              v-model="formData.des"
              maxlength="500"
              rows="5"
              @focus="handleFocus('des')"
              @blur="handleBlur('des')"
            ></textarea>
            <label class="floating-label" :class="{ 'active': isFocus.des || formData.des.trim() }">
              请详细描述问题
            </label>
          </view>
          <text class="word-count">{{ formData.des.length }}/500</text>
        </view>

        <!-- 7. 紧急程度（必选） -->
        <view class="form-item">
          <text class="form-label">紧急程度 *</text>
          <picker 
            class="form-picker"
            mode="selector"
            :range="priorityOptions"
            :range-key="'label'"
            :value="priorityIndex"
            @change="onPriorityChange"
          >
            <view class="picker-view">
              {{ priorityIndex !== null ? priorityOptions[priorityIndex].label : '请选择紧急程度' }}
              <i class="fa fa-angle-down"></i>
            </view>
          </picker>
        </view>

        <!-- 8. 上传图片（可选） -->
        <view class="form-item">
          <text class="form-label">上传图片（可选）</text>
          <view class="upload-container">
            <view 
              class="upload-area"
              @click="chooseImage"
              v-if="images.length < maxImages"
            >
              <i class="fa fa-cloud-upload"></i>
              <text class="upload-text">点击上传</text>
            </view>
            <view class="image-preview" v-for="(img, index) in images" :key="index">
              <image :src="img" mode="aspectFill" class="preview-img" />
              <view class="delete-img" @click.stop="deleteImage(index)">
                <i class="fa fa-times"></i>
              </view>
            </view>
          </view>
        </view>

        <!-- 9. 提交按钮 -->
        <button 
          class="submit-btn"
          form-type="submit"
          :disabled="!canSubmit || isSubmitting"
        >
          <template v-if="isSubmitting">{{ isEdit ? '修改中...' : '提交中...' }}</template>
          <template v-else>{{ isEdit ? '确认修改' : '提交工单' }}</template>
        </button>
      </form>
    </view>
  </view>
</template>

<script>
import BMap from '../../../libs/bmap-wx.min.js';
import request from '@/api/request.js';

export default {
  data() {
    return {
      statusBarHeight: 0,
      isEdit: false,
      products: [],
      productIndex: null,
      images: [],
      maxImages: 1,
      isSubmitting: false,
      retryCount: 0, // 重试次数
      maxRetry: 2, // 最大重试次数
      priorityOptions: [
        { label: '普通', value: 1 },
        { label: '紧急', value: 2 }
      ],
      priorityIndex: null,
      formData: {
        id: '',               // 工单ID（修改时核心参数）
        title: '',
        des: '',
        name: '',
        phone: '',
        address: '',
        longitude: null,
        latitude: null,
        productId: null,
        priorityType: null,
        customerId: '',
        pic: ''
      },
      bmapSdk: new BMap({ ak: 'QRlTU79HkzFsBFB3x8FrBve4OulDFqQT' }),
      isFocus: {
        title: false,
        name: false,
        phone: false,
        address: false,
        des: false
      },
      imageBaseUrl: 'http://47.96.93.244:8084/'
    };
  },
  
  computed: {
    canSubmit() {
      return (
        this.formData.productId !== null &&
        this.formData.title.trim() &&
        this.formData.des.trim() &&
        this.formData.name.trim() &&
        this.formData.phone.trim() &&
        this.formData.phone.length === 11 &&
        this.formData.address.trim() &&
        this.formData.longitude !== null &&
        this.formData.latitude !== null &&
        this.formData.priorityType !== null &&
        (this.isEdit ? !!this.formData.id : true) // 修改时必须有ID才允许提交
      );
    }
  },
  
  onLoad(options) {
    // 检查登录状态
    if (!this.checkLoginStatus()) return;
    
    // 获取状态栏高度
    this.getSystemInfo();
    
    // 打印所有接收的参数（调试用）
    console.log('【修改页】接收的原始参数:', options);
    
    // 判断是否为修改模式
    this.isEdit = options.isEdit === 'true';
    if (this.isEdit) {
      // 核心：ID接收与校验
      if (!options.id) {
        uni.showToast({ title: '未获取到工单ID，无法修改', icon: 'none' });
        setTimeout(() => uni.navigateBack(), 3000);
        return;
      }
      
      // 解码ID（处理特殊字符）
      try {
        this.formData.id = decodeURIComponent(options.id);
        if (!this.formData.id) {
          throw new Error('ID解码后为空');
        }
        console.log('【修改页】成功获取工单ID:', this.formData.id);
      } catch (e) {
        uni.showToast({ title: '工单ID解析失败', icon: 'none' });
        console.error('ID解析错误:', e);
        setTimeout(() => uni.navigateBack(), 3000);
        return;
      }
      
      // 解析其他参数
      this.formData.title = decodeURIComponent(options.title || '');
      this.formData.des = decodeURIComponent(options.des || '');
      this.formData.name = decodeURIComponent(options.name || '');
      this.formData.phone = decodeURIComponent(options.phone || '');
      this.formData.productId = Number(decodeURIComponent(options.productId || ''));
      this.formData.priorityType = Number(decodeURIComponent(options.priorityType || ''));
      this.formData.customerId = decodeURIComponent(options.customerId || '');
      this.formData.pic = decodeURIComponent(options.pic || '');
      
      // 处理经纬度
      const addressParts = (options.address || '').split(',');
      if (addressParts.length === 2) {
        const latitude = addressParts[0] || '';
        const longitude = addressParts[1] || '';
        if (latitude && longitude && !isNaN(Number(latitude)) && !isNaN(Number(longitude))) {
          this.formData.latitude = latitude;
          this.formData.longitude = longitude;
          this.reverseGeocode(longitude, latitude);
        } else {
          this.formData.longitude = null;
          this.formData.latitude = null;
          this.formData.address = '经纬度格式错误';
        }
      } else {
        this.formData.longitude = null;
        this.formData.latitude = null;
        this.formData.address = '地址参数格式错误';
      }
      
      // 回显图片
      if (this.formData.pic) {
        this.images = [this.imageBaseUrl + this.formData.pic];
      }
    }
    
    // 加载产品列表
    this.getProductList();
  },
  
  onReady() {
    if (this.isEdit) {
      this.setEditDefaultValue();
    }
  },
  
  methods: {
    getSystemInfo() {
      try {
        const systemInfo = uni.getSystemInfoSync();
        this.statusBarHeight = systemInfo.statusBarHeight;
      } catch (e) {
        console.error('获取系统信息失败：', e);
        this.statusBarHeight = 20;
      }
    },
    
    checkLoginStatus() {
      const token = uni.getStorageSync('token');
      const userInfo = uni.getStorageSync('userInfo');
      
      if (!token || !userInfo) {
        uni.showToast({ title: '请先登录', icon: 'none' });
        setTimeout(() => {
          uni.redirectTo({ url: '/pages/login/login' });
        }, 1000);
        return false;
      }
      
      if (!this.isEdit) {
        this.formData.customerId = userInfo.customerId || '';
      }
      return true;
    },
    
    navigateBack() {
      uni.navigateBack();
    },
    
    async getProductList() {
      try {
        uni.showLoading({ title: '加载产品列表...' });
        const productData = await request.postJson(
          '/api/productInfo/getAvailableProducts', 
          {}, 
          true
        );
        uni.hideLoading();
        this.products = productData.map(item => ({
          id: item.id,
          name: item.productName
        }));
        if (this.isEdit) {
          this.setEditDefaultValue();
        }
        if (this.products.length === 0) {
          uni.showToast({ title: '暂无可用产品', icon: 'none' });
        }
      } catch (error) {
        uni.hideLoading();
        console.error('产品列表请求失败：', error);
        if (error.code === 100003) {
          uni.showToast({ title: '登录已失效，请重新登录', icon: 'none' });
          uni.removeStorageSync('token');
          setTimeout(() => {
            uni.redirectTo({ url: '/pages/login/login' });
          }, 1000);
        } else {
          uni.showToast({ title: error.msg || '网络异常', icon: 'none' });
        }
      }
    },
    
    setEditDefaultValue() {
      if (this.formData.productId && this.products.length > 0) {
        const index = this.products.findIndex(item => item.id === this.formData.productId);
        this.productIndex = index > -1 ? index : null;
      }
      
      if (this.formData.priorityType) {
        const index = this.priorityOptions.findIndex(item => item.value === this.formData.priorityType);
        this.priorityIndex = index > -1 ? index : 0;
      } else {
        this.priorityIndex = 0;
      }
    },
    
    onProductChange(e) {
      this.productIndex = e.detail.value;
      this.formData.productId = this.products[e.detail.value].id;
    },
    
    onPriorityChange(e) {
      this.priorityIndex = e.detail.value;
      this.formData.priorityType = this.priorityOptions[e.detail.value].value;
    },
    
    openMapWithCurrentLocation() {
      const that = this;
      uni.getSetting({
        success(res) {
          if (!res.authSetting['scope.userLocation']) {
            uni.authorize({
              scope: 'scope.userLocation',
              success() {
                that._handleMapInitLocation();
              },
              fail() {
                uni.showToast({ title: '请开启位置权限', icon: 'none' });
              }
            });
          } else {
            that._handleMapInitLocation();
          }
        },
        fail(err) {
          console.error('获取权限失败：', err);
          uni.showToast({ title: '权限检查失败', icon: 'none' });
        }
      });
    },
    
    _handleMapInitLocation() {
      const inputAddr = this.formData.address.trim();
      if (inputAddr) {
        this._parseAddressToLatLng(inputAddr);
      } else {
        this._getCurrentLocation();
      }
    },
    
    _parseAddressToLatLng(address) {
      const that = this;
      uni.showLoading({ title: '解析地址...', mask: true });
      this.bmapSdk.geocoding({
        address: address,
        success(res) {
          uni.hideLoading();
          if (res.wxMarkerData && res.wxMarkerData.length > 0) {
            const { longitude, latitude } = res.wxMarkerData[0];
            that._openMapChooseLocation(longitude, latitude);
          } else {
            uni.showToast({ title: '解析失败，使用当前位置', icon: 'none' });
            that._getCurrentLocation();
          }
        },
        fail(err) {
          uni.hideLoading();
          console.error('地址解析失败：', err);
          uni.showToast({ title: '解析失败，使用当前位置', icon: 'none' });
          that._getCurrentLocation();
        }
      });
    },
    
    _getCurrentLocation() {
      const that = this;
      uni.getLocation({
        type: 'gcj02',
        success(res) {
          that._openMapChooseLocation(res.longitude, res.latitude);
        },
        fail(err) {
          console.error('定位失败：', err);
          if (err.errMsg.includes('system permission')) {
            uni.showToast({ title: '请打开手机定位服务', icon: 'none' });
          } else {
            uni.showToast({ title: '定位失败，请重试', icon: 'none' });
          }
        }
      });
    },
    
    _openMapChooseLocation(longitude, latitude) {
      const that = this;
      uni.chooseLocation({
        latitude: latitude,
        longitude: longitude,
        success(res) {
          that.formData.address = res.address;
          that.formData.longitude = res.longitude;
          that.formData.latitude = res.latitude;
          uni.showToast({ title: '选点成功', icon: 'success' });
        },
        fail(err) {
          console.error('地图选点失败：', err);
          if (err.errMsg !== 'chooseLocation:fail cancel') {
            uni.showToast({ title: '选点失败，请重试', icon: 'none' });
          }
        }
      });
    },
    
    handleBlur(field) {
      this.isFocus[field] = false;
      if (field !== 'address') return;
      
      const inputAddr = this.formData.address.trim();
      if (!inputAddr) {
        this.formData.longitude = null;
        this.formData.latitude = null;
        return;
      }
      
      const that = this;
      uni.showLoading({ title: '解析地址中...', mask: true });
      this.bmapSdk.geocoding({
        address: inputAddr,
        success(res) {
          uni.hideLoading();
          if (res.wxMarkerData && res.wxMarkerData.length > 0) {
            that.formData.longitude = res.wxMarkerData[0].longitude;
            that.formData.latitude = res.wxMarkerData[0].latitude;
            uni.showToast({ title: '地址解析成功', icon: 'none' });
          } else {
            that.formData.longitude = null;
            that.formData.latitude = null;
            uni.showToast({ title: '无法解析该地址', icon: 'none' });
          }
        },
        fail(err) {
          uni.hideLoading();
          that.formData.longitude = null;
          that.formData.latitude = null;
          console.error('地址解析失败：', err);
          uni.showToast({ title: '解析失败，请重试', icon: 'none' });
        }
      });
    },
    
    handleFocus(field) {
      this.isFocus[field] = true;
    },
    
    chooseImage() {
      if (this.images.length >= this.maxImages) {
        uni.showToast({ title: `最多上传${this.maxImages}张图片`, icon: 'none' });
        return;
      }
      
      uni.chooseImage({
        count: this.maxImages - this.images.length,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          const validImages = res.tempFilePaths.filter((path, index) => {
            const size = res.tempFiles[index].size;
            if (size > 5 * 1024 * 1024) {
              uni.showToast({ title: '图片不能超过5MB', icon: 'none' });
              return false;
            }
            return true;
          });
          this.images = this.images.concat(validImages);
        }
      });
    },
    
    deleteImage(index) {
      this.images.splice(index, 1);
    },
    
    reverseGeocode(longitude, latitude) {
      this.formData.address = '地址解析中...';
      this.bmapSdk.regeocoding({
        location: `${latitude},${longitude}`,
        success: (res) => {
          if (res && res.result && res.result.address) {
            this.formData.address = res.result.address;
          } else {
            this.formData.address = '地址解析失败';
          }
        },
        fail: (err) => {
          console.error('逆地理编码失败:', err);
          this.formData.address = `解析失败（${err.errMsg}）`;
        }
      });
    },
    
    async submitForm() {
      if (!this.checkLoginStatus()) return;
      
      // 再次校验ID（最终保障）
      if (this.isEdit && !this.formData.id) {
        uni.showToast({ title: '工单ID丢失，请返回重试', icon: 'none' });
        return;
      }
      
      // 重置重试次数
      this.retryCount = 0;
      this.isSubmitting = true;
      let hasError = false; // 新增：标记是否发生错误
      try {
        const submitData = {
          id: this.formData.id,
          title: this.formData.title.trim(),
          des: this.formData.des.trim(),
          name: this.formData.name.trim(),
          phone: this.formData.phone.trim(),
          address: `${this.formData.longitude},${this.formData.latitude}`,
          productId: this.formData.productId,
          priorityType: this.formData.priorityType,
          customerId: this.formData.customerId,
          type: 0
        };
        
        console.log('【提交参数】', submitData);
        
        if (this.isEdit) {
          await this.updateWorkorder(submitData);
        } else {
          await this.createWorkorder(submitData);
        }
        
        uni.showToast({ 
          title: this.isEdit ? '修改成功' : '创建成功', 
          icon: 'success' 
        });
        setTimeout(() => {
          uni.redirectTo({ url: '/pages/User/workorder/workorder' });
        }, 1500);
        
      } catch (error) {
        hasError = true; // 发生错误时标记
        console.error(`${this.isEdit ? '修改' : '创建'}工单失败：`, error);
        
        if (error.message.includes('服务器繁忙') && this.retryCount < this.maxRetry) {
          this.retryCount++;
          uni.showToast({ 
            title: `服务器繁忙，正在重试（${this.retryCount}/${this.maxRetry}）...`, 
            icon: 'none',
            duration: 1500
          });
          setTimeout(() => {
            this.submitForm();
          }, 1000 * this.retryCount);
          return;
        }
        
        uni.showToast({ 
          title: error.message || `${this.isEdit ? '修改' : '创建'}失败，请重试`, 
          icon: 'none' 
        });
        
        if (error.code === 100003) {
          uni.removeStorageSync('token');
          setTimeout(() => {
            uni.redirectTo({ url: '/pages/login/login' });
          }, 1000);
        }
      } finally {
        // 修复：使用hasError标记，避免直接引用error变量
        if (!hasError || !(this.retryCount < this.maxRetry)) {
          this.isSubmitting = false;
        }
      }
    },
    
    createWorkorder(submitData) {
      return new Promise((resolve, reject) => {
        const token = uni.getStorageSync('token');
        const picFile = this.images.length > 0 ? this.images[0] : null;
        
        uni.uploadFile({
          url: request.baseURL.order + '/api/workOrderInfo/create',
          method: 'POST',
          header: { 'Token': token },
          formData: {
            saveBO: JSON.stringify(submitData)
          },
          filePath: picFile,
          name: 'picFile',
          success: (res) => {
            console.log('【创建工单响应】', res.data);
            const data = JSON.parse(res.data);
            if (data.code === 0) {
              resolve(data);
            } else {
              reject(new Error(data.msg || '创建工单失败'));
            }
          },
          fail: (err) => {
            reject(new Error('网络请求失败：' + err.errMsg));
          }
        });
      });
    },
    
    updateWorkorder(submitData) {
      return new Promise((resolve, reject) => {
        // 最后一道防线：校验ID
        if (!submitData.id) {
          reject(new Error('工单ID为空，无法修改！'));
          return;
        }
        
        // 检查Token有效性
        const token = uni.getStorageSync('token');
        if (!token) {
          reject(new Error('登录已失效，请重新登录'));
          return;
        }
        
        // 处理图片上传
        const uploadImage = async () => {
          if (this.images.length > 0 && this.images[0].indexOf('tmp') > -1) {
            return new Promise((resolveImg, rejectImg) => {
              uni.uploadFile({
                url: request.baseURL.order + '/api/upload',
                filePath: this.images[0],
                name: 'file',
                header: { 'Token': token },
                success: (res) => {
                  console.log('【图片上传响应】', res.data);
                  const data = JSON.parse(res.data);
                  if (data.code === 0) {
                    resolveImg(data.data.fileUrl);
                  } else {
                    rejectImg(new Error('图片上传失败: ' + data.msg));
                  }
                },
                fail: (err) => {
                  rejectImg(new Error('图片上传失败: ' + err.errMsg));
                }
              });
            });
          }
          return this.formData.pic;
        };
        
        uploadImage().then(imgUrl => {
          submitData.pic = imgUrl;
          
          // 关键修改：将工单数据包装到saveBO参数中
          const requestData = {
            saveBO: JSON.stringify(submitData)
          };

          uni.request({
            url: request.baseURL.order + '/api/workOrderInfo/updateWithPic',
            method: 'POST',
            header: {
              'Content-Type': 'application/x-www-form-urlencoded',
              'Token': token
            },
            data: requestData,
            success: (res) => {
              console.log('【修改工单响应】', res.data);
              if (res.data.code === 0) {
                resolve(res.data);
              } else {
                reject(new Error(res.data.msg || `修改工单失败（code: ${res.data.code || '未知'}）`));
              }
            },
            fail: (err) => {
              reject(new Error('网络请求失败: ' + err.errMsg));
            }
          });
        }).catch(err => {
          reject(err);
        });
      });
    }
  }
};
</script>

<style scoped>
.container {
  background-color: #f5f7fa;
  min-height: 100vh;
}

.navbar {
  background: #5555ff;
  display: flex;
  align-items: center;
  padding: 0 15px;
  position: relative;
  box-sizing: border-box;
}
.back-btn {
  color: #fff;
  font-size: 20px;
}
.title {
  color: #fff;
  font-size: 18px;
  font-weight: 500;
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}

.form-container {
  padding: 15px;
}

.form-item {
  margin-bottom: 24px;
}
.form-label {
  display: block;
  color: #272e3b;
  font-size: 14px;
  margin-bottom: 4px;
  font-weight: 500;
}

.form-picker {
  width: 100%;
}
.picker-view {
  width: 100%;
  background-color: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  padding: 15px 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #333;
  font-size: 16px;
  box-sizing: border-box;
  height: 50px;
}
.picker-view .fa {
  color: #86909c;
}

.input-group {
  position: relative;
  margin-top: 4px;
}
.form-input {
  width: 100%;
  background-color: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  padding: 16px 12px 6px 12px;
  font-size: 16px;
  color: #333;
  box-sizing: border-box;
  height: 56px;
  line-height: 1.5;
}

.floating-label {
  position: absolute;
  left: 12px;
  top: 14px;
  font-size: 14px;
  color: #909399;
  pointer-events: none;
  transition: all 0.2s ease;
  background-color: #fff;
  padding: 0 4px;
}
.floating-label.active {
  opacity: 0;
  visibility: hidden;
  transform: translateY(-10px);
}

.textarea-group {
  height: auto;
}
.textarea-group .form-input {
  height: auto;
  min-height: 120px;
  padding-top: 16px;
}

.map-btn {
  width: 100%;
  background: #f0f2f5;
  color: #165dff;
  border-radius: 8px;
  padding: 12px 0;
  font-size: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: none;
  margin-top: 8px;
}
.map-btn .fa {
  margin-right: 6px;
}
.map-btn-hover {
  background: #e5e9f2;
}

.word-count {
  display: block;
  text-align: right;
  color: #86909c;
  font-size: 12px;
  margin-top: 5px;
}

.upload-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}
.upload-area {
  width: 80px;
  height: 80px;
  border: 2px dashed #e5e6eb;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #86909c;
  cursor: pointer;
}
.upload-area .fa {
  font-size: 24px;
  margin-bottom: 5px;
}
.upload-text {
  font-size: 12px;
}
.image-preview {
  width: 80px;
  height: 80px;
  border-radius: 8px;
  position: relative;
  overflow: hidden;
}
.preview-img {
  width: 100%;
  height: 100%;
}
.delete-img {
  position: absolute;
  top: -5px;
  right: -5px;
  width: 20px;
  height: 20px;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  font-size: 12px;
  cursor: pointer;
}

.submit-btn {
  width: 100%;
  background: #165dff;
  color: #fff;
  padding: 15px 0;
  border-radius: 8px;
  font-size: 17px;
  margin-top: 24px;
  border: none;
}
.submit-btn:disabled {
  background: #86909c;
}

.parse-status {
  display: block;
  margin-top: 5px;
  font-size: 12px;
  color: #00b42a;
}
.parse-status.error {
  color: #f53f3f;
}
.parse-status .fa {
  margin-right: 3px;
}
</style>
